package com.vagavaga.bizworld.jpatx;

import java.util.HashMap;

import javax.persistence.EntityManager;

final class TxManager {
    private static ThreadLocal<HashMap<String, EntityManager>> currentManager = new ThreadLocal<HashMap<String, EntityManager>>() {
        @Override
        protected HashMap<String, EntityManager> initialValue() {
            return new HashMap<String, EntityManager>();
        };
    };

    private TxManager() {
    // no creation;
    }

    public static EntityManager currentEntityManager(String persistenceUnitName) {
        return currentManager.get().get(persistenceUnitName);
    }

    public static boolean isInTransaction(String dsname) {
        return currentEntityManager(dsname) != null;
    }

    public static void bind(String persistenceUnitName, EntityManager em) throws IllegalStateException {
        if (isInTransaction(persistenceUnitName)) {
            throw new IllegalStateException("Thread is already bound");
        }
        currentManager.get().put(persistenceUnitName, em);
    }

    public static void unbind(String persistenceUnitName) {
        currentManager.get().remove(persistenceUnitName);
    }

}
